#pragma once

#include "mlog.h"
#include "napi.h"
#include "thread/thread.h"
#include <bits/alltypes.h>
#include <js_native_api_types.h>
#include "gles/glesmain.h";

static void Dispatch_OnInit() {}
static void Dispatch_OnUpdate() {}
static void StartThread_VSync() {}
// 新的初始化接口
static napi_value Gfx_Init(napi_env env, napi_callback_info info) {
    auto t = getThreadID();
    auto glesmain_ = getGlesmain();
    // Create GLES context.
    glesmain_->GFX_Init();
    

    // DoCallback
    {
        size_t argc = 2;
        napi_value argv[2];
        napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
        glesmain_->cb_env=env;
        napi_create_reference(env, argv[0], 1, &glesmain_->ref_oninit);
        napi_create_reference(env, argv[1], 1, &glesmain_->ref_onupdate);
    }
    
    //触发Init事件
    glesmain_->Dispatch_OnInit();
 

    // 开一个垂直同步监视线程
    glesmain_->StartVSyncThread();
    return nullptr;
}
static napi_value Gfx_GetRegOutput(napi_env env, napi_callback_info info) {
    // 复用同一块内存
    auto glesmain_ = getGlesmain();
    napi_value reg_value;
    {
        napi_create_external_arraybuffer(
            env, (void *)glesmain_->Reg_Output, 64, 
            [](napi_env env, void *data, void *hint) {},// 这个finallize 不能为空
            nullptr, 
            &reg_value);
    }
    return  reg_value;
}
static napi_value Gfx_GetRegInput(napi_env env, napi_callback_info info) {
    // 复用同一块内存
    auto glesmain_ = getGlesmain();
    napi_value reg_value;
    {
        napi_create_external_arraybuffer(
            env, (void *)glesmain_->Reg_Input, 64,
            [](napi_env env, void *data, void *hint) {}, // 这个finallize 不能为空
            nullptr, &reg_value);
    }
    return reg_value;
}
static napi_value Gfx_Commit(napi_env env, napi_callback_info info) 
{
    auto glesmain_ = getGlesmain();
    glesmain_->Cmd_Commit();
    return nullptr; 
}
static napi_value Gfx_Read(napi_env env, napi_callback_info info) {
    auto glesmain_ = getGlesmain();
    glesmain_->Cmd_Read();
    return nullptr;
}
void ExportNAPIFunction_GFX(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        //{"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr}
        {"Gfx_Init", nullptr, &Gfx_Init, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"Gfx_GetRegOutput", nullptr, &Gfx_GetRegOutput, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"Gfx_GetRegInput", nullptr, &Gfx_GetRegInput, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"Gfx_Commit", nullptr, &Gfx_Commit, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"Gfx_Read", nullptr, &Gfx_Read, nullptr, nullptr, nullptr, napi_default, nullptr},
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
}